#include "GUIButton.h"
#include "IRenderer.h"
#include "OnMouseLeftDownEvent.h"
#include "OnMouseLeftUpEvent.h"
#include "GUIWindow.h"

GUIButton::GUIButton()
{
	m_backgroundColor = 0xFFDDDDDD;
	m_fontColor = 0x00000000;
	m_font = HashedString("Arial");
	m_visible = true;
	m_enabled = true;
	m_dimensions = Maths::Point<unsigned int>(1, 1);
}

void GUIButton::Paint()
{
	if (m_visible)
	{
		// Render background
		Maths::Matrix transform;
		transform.Translate(m_location.X, m_location.Y, 0.0f);
		transform.Scale(m_dimensions.X, m_dimensions.Y, 1.0f);

		Renderer->SetColor(m_backgroundColor);
		Renderer->PushTexture(m_background);
		Renderer->PushModelViewMatrix(transform);
		Renderer->Render(*(m_shape.getShape()));
		Renderer->PopModelViewMatrix();
		Renderer->PopTexture();
		Renderer->SetColor(0xFFFFFFFF);

		// Render text
		Renderer->PrintFont(m_font, m_fontColor, m_parentLocation.X + m_location.X+4, m_parentLocation.Y + m_location.Y+4, m_text.c_str());
	}
}
void GUIButton::Text( std::string& title )
{
	m_text = title;
}
std::string GUIButton::Text() const
{
	return m_text;
}
void GUIButton::Font( std::string& font )
{
	m_font = HashedString(font);
}
void GUIButton::Font( HashedString& font )
{
	m_font = font;
}
HashedString GUIButton::Font() const
{
	return m_font;
}
void GUIButton::FontColor( unsigned int color )
{
	m_fontColor = color;
}
unsigned int GUIButton::FontColor() const
{
	return m_fontColor;
}
void GUIButton::Background( std::string& background )
{
	m_background = HashedString(background);
}
void GUIButton::Background( HashedString& background )
{
	m_background = background;
}
HashedString GUIButton::Background() const
{
	return m_background;
}
unsigned int GUIButton::BackgroundColor()
{
	return m_backgroundColor;
}
void GUIButton::BackgroundColor( unsigned int color )
{
	m_backgroundColor = color;
}
bool GUIButton::ReceiveEvent( IEvent& event )
{
	if (m_enabled && m_visible)
	{
#pragma region MouseInput
		if (event.Type() == OnMouseLeftUpEvent::type)
		{
			OnMouseLeftUpEvent& mouseEvent = static_cast<OnMouseLeftUpEvent&>(event);
			int x = mouseEvent.Coords().X;
			int y = mouseEvent.Coords().Y;
			int absX = m_location.X + (int)m_parentLocation.X;
			int absY = m_location.Y + m_parentLocation.Y;
		
			if ((x > absX) && (x < absX + (int)m_dimensions.X) &&
				(y > absY) && (y < absY + (int)m_dimensions.Y))
			{
				if (m_clickFunction.isValid())
					(*m_clickFunction)();
				return true;
			}
		}
#pragma endregion
	}
	return false;
}
void GUIButton::ClickFunction( Pointer<Functor>& function )
{
	m_clickFunction = function;
}